
#define FREQ_817_CMD 0x03

typedef void (*CallBackFunction) (byte dataType,byte data[],byte len);

class SwitchData{
public:
/*
 * 协议类型:
 * 0xA1:自协议
 * 1.817/Q900
*/
  byte RadioType=0;
  unsigned long FREQ =0;//频率

  //接收数据
  void CheckData(CallBackFunction callback){
    byte b=Serial.read();
    
    if(b==0xFE)
    {      
      ReadBuff(7);
      
      callback(1,radioBuff,6);
    }
    else if(RadioType==0)
    {
      callback(0,{0x00},0);
    }
    else{
      if(RadioType==1 || RadioType==2)
      {
        FTQData(b);
        callback(2,{0x00},0);
      }    
    }
  }
  //发送数据
  void GetData(){
    switch(RadioType)
    {     
      case 1:
        Send900Data();
      break;
      case 2:
        Send900Data();
      break;
    }
  }
  


private:
  byte radioBuff[24];
  void SendData(byte data[],byte len){
    for (byte i=0; i<len; i++)
    {
      Serial.write(data[i]);
      //Serial.println(data[i],HEX);        // 调试输出
      //delay(10);
    }
    Serial.flush();
  }

  void ReadBuff(byte dataLen)
  {
    memset(radioBuff, 0x00,dataLen); 
    Serial.readBytes(radioBuff,dataLen); 
    /*radioBuff[0]=b;
    
    for(byte i=i;i<dataLen-1;i++)
    {
      byte b=Serial.read();     
      radioBuff[i]=Serial.read();     
      Serial.write(b); 
      delay(10);
    }*/
  }

  void ReadBuff(byte cmd,byte dataLen)
  {
    byte tb[dataLen-1]={0x00};
    Serial.readBytes(tb,dataLen-1); 
    
    memset(radioBuff, 0x00,dataLen);     
    radioBuff[0]=cmd;   
     
    for(byte i=1;i<dataLen;i++)
    {  
      radioBuff[i]=tb[i-1];  
    }
  }

  void Send900Data(){
    memset(radioBuff, 0x00,5); 
    radioBuff[4] = FREQ_817_CMD;
    SendData(radioBuff,5);
  }

  //FT817/Q900
  void FTQData(byte b){ 
    ReadBuff(b,5);
      
    FREQ = 0;
    for (byte i = 0; i < 4; i++)
    {
  
      FREQ *= 10;
      FREQ += radioBuff[i] >> 4;
      FREQ *= 10;
      FREQ += radioBuff[i] & 0x0f;
    }
    
    FREQ=FREQ/100000;
   
  }  
  
};

class Commend{
public:
  /*
  字节数组转字符串
  */
  static void B2CA(char *ref,byte data[],byte staIndex,byte len)
  {
    
    //从EEPROM中逐个取出每一位的值，并链接
    for (int i = staIndex; i <= len; i++){      
      if(data[i]!=255)
      {      
        ref[i] = char(data[i]);
      }   
    }    
  }
  
    
  /*
   * 数字转HEX数组
   * Num:无限定符长整型数字
   * dest:指针引用数组
   * len:指定补齐位长,0不指定
  */
  
  
  static unsigned int HexToInt(byte D1,byte D2)
  { 
     String hex=Byte2HEXStr(D1);
     hex+=Byte2HEXStr(D2);
     hex.toUpperCase();
    
     char buf[hex.length()+1] ;
     hex.toCharArray(buf,hex.length()+1);
     
     unsigned int rt=0;
     rt = strtol(buf, NULL, 16);   
      
     return rt;
  }

  static String Byte2HEXStr(byte dt)
  {
     String tmp=String(dt,HEX);    
     if(tmp.length()<=1)tmp="0"+tmp;
     return tmp;
  }
  
};
